/*
 * Create:      柿子
 * CreateDate:  2022/08/23
 * Describe：   库房 - 视光产品基本信息维护（集团）/产品基本信息（视光）
 * */
import React, { Component } from 'react';
import { Row, Col, Card, Button, Input, Select, Modal, message, Icon, Popconfirm, Checkbox, Radio, Divider, Badge, Spin } from 'antd';
import { Util, dayFormat } from 'tools';
import { handleExcel } from 'tools/handleExcel';
import store from 'store';
import moment from 'moment';
import PubilcTablePagination from 'pages/common/PubilcTablePagination.jsx';
import ReturnOrder from '../glassesManagement/component/ReturnOrder';
import DynamicRenderingForm from 'pages/common/DynamicRenderingForm';
import PublicTableEditable from 'pages/common/PublicTableEditable';
import PublicModalTable from 'pages/common/PublicModalTable';
import RangeDatePicker from 'components/rangePicker/index';
import SupplierAuditRecord from 'pages/optometry/supplier/component/SupplierAuditRecord';
import iconListvisits from 'assets/images/icon_listvisits.png';
import './style/index.less';

class EssentialInformationGroup extends Component {
  constructor(props) {
    super(props);
    let userData = React.$getSessionData();
    this.state = {
      userData,
      columns: [],
      totalWidth: 850,
      tableData: [],
      total: 0,
      page: 1,
      pageSize: 20,
      loading: false,
      selectData: {},
      queryParams: {
        desc: undefined,
        startDate: undefined,
        endDate: undefined,
        stkSubCatID: undefined,
        useFlag: true,
        status: '', // 审核状态
        statusType: undefined, // 审核类型
      },
      rowID: '',
      rowData: {},
      copyRowData: {},
      baseInfoFormData: [], // 基本信息表单数据
      chargesFormData: [],
      hospInfoFormData: [], // 原医院基本信息
      aliasColumns: [],
      exportLoading: false, // 导出loading
      saveLoading: false, // 保存loading
      userOrganizationCloumns: [], // 使用机构表头数据
      userOrganizationTableData: [],
      userOrganizationTotalWidth: 200,
      authorizationColumns: [],
      authorizationValue: undefined,
      categoryData: {}, // 界面参数
      queryHeight: 78, // 查询栏高度
      detailLoading: false,
      changeFlag: true,
      conserveFormData: [], // 养护模块
    };
    this.queryRef = React.createRef();

    this.staticColumns = [{
      key: 1,
      title: '产品代码',
      dataIndex: 'stockCode',
      align: 'center',
      width: 160
    }, {
      key: 2,
      title: '产品名称',
      dataIndex: 'stockDesc',
      align: 'center',
      width: 300
    }, {
      key: 3,
      title: '库存子类',
      dataIndex: 'stkSubCatDesc',
      align: 'center',
      width: 150
    }, {
      key: 4,
      title: '入库单位',
      dataIndex: 'unitDesc',
      align: 'center',
      width: 100
    }, {
      key: 5,
      title: '使用机构',
      dataIndex: 'usedCount',
      align: 'center',
      width: 100
    }, {
      key: 6,
      title: '状态',
      dataIndex: 'statusDesc',
      align: 'center',
      width: 100
    }];

    this.staticChargesFormData = [{
      key: 1,
      dataIndex: 'chargePCID',
      title: '物价分类',
      typeCode: 'Select',
      required: 'Y',
    }, {
      key: 2,
      dataIndex: 'chargeECID',
      title: '核算项目分类',
      typeCode: 'Select',
      required: 'Y',
    }, {
      key: 3,
      dataIndex: 'chargeICID',
      title: '住院收费分类',
      typeCode: 'Select',
      required: 'Y',
    }, {
      key: 4,
      dataIndex: 'chargeACID',
      title: '会计科目',
      typeCode: 'Select',
      required: 'Y',
    }, {
      key: 5,
      dataIndex: 'chargeMCID',
      title: '病案分类',
      typeCode: 'Select',
      required: 'Y',
    }, {
      key: 6,
      dataIndex: 'chargeOCID',
      title: '门诊收据费用',
      typeCode: 'Select',
      required: 'Y',
    }, {
      key: 7,
      dataIndex: 'chargeTCID',
      title: '收费分类',
      typeCode: 'Select',
      required: 'Y',
    }];

    this.staticHospInfoFormData = [{
      dataIndex: 'manfID',
      title: '生产厂家',
      required: 'Y',
      typeCode: 'Select',
      col: 8
    }, {
      dataIndex: 'appPrefixID',
      title: '批准文号前缀',
      required: 'Y',
      typeCode: 'Select',
      col: 8
    }, {
      dataIndex: 'apprNo',
      title: '批准文号',
      typeCode: 'Input',
      required: 'Y',
      col: 8
    }, {
      dataIndex: 'apprExpDate',
      title: '批文有效期',
      typeCode: 'Date',
      required: 'Y',
      col: 8
    }, {
      dataIndex: 'regCertNo',
      title: '注册证号',
      typeCode: 'Input',
      col: 8
    }, {
      dataIndex: 'regCertExpDate',
      title: '注册证有效期',
      typeCode: 'Date',
      col: 8
    }];
  }

  componentDidMount() {
    let newCategory;
    if ('paras' in this.props && this.props.paras && this.props.paras.params) { // 侧菜单获取类别参数
      newCategory = this.props.paras.params;
    } else {
      if ('location' in this.props && this.props.location.state && this.props.location.state.params) { // 头菜单获取类别参数
        newCategory = this.props.location.state.params;
        React.$setSessionData('EssentialInformationGroup', newCategory, false);
      } else { // 头菜单刷新界面时获取类别
        newCategory = React.$getSessionData('EssentialInformationGroup', false);
      }
    }
    // 界面类型 - create(制单) / reviewed(审核)
    let categoryData = Util.getObjByUrlStr(newCategory);
    console.log("categoryData", categoryData)
    this.setState({ categoryData }, () => {
      this.getSelectData();
      this.getTableColumns();
      // this.getAliasColumns();
      this.getHospitalAuthorization();
      // this.getChargesFormData();
      this.getHospInfoFormData();
      this.getConserveFormData();
    });
  }

  componentWillUnmount() {
    this.setState = (state, callback) => { return; }
  }

  // 获取下拉数据
  getSelectData = async () => {
    try {
      let { userData, categoryData, queryParams } = this.state;
      let data = {
        params: [{
          // S - 提交页面; A - 审核页面  
          type: categoryData?.interfaceType === 'reviewed' ? 'A' : 'S',
          hospID: userData?.hospID || ''
        }]
      }
      let res = await React.$asyncPost(this, '17060001', data);
      let selectData = res || {};
      let status = selectData?.status || [];
      let activeStatusArr = status && status.filter(item => item.default === 'Y');
      queryParams.status = activeStatusArr && activeStatusArr.length > 0 ? activeStatusArr[0]?.id : ''; // 默认审核状态
      if (categoryData?.interfaceType === 'reviewed') { // 默认状态类型
        let statusType = selectData?.statusType || [];
        let activeStatusTypeArr = statusType && statusType.filter(item => item.default === 'Y');
        queryParams.statusType = activeStatusTypeArr && activeStatusTypeArr.length > 0 ? activeStatusTypeArr[0]?.id : '';
        // 默认日期
        queryParams.startDate = selectData?.startDate || moment().format(dayFormat);
        queryParams.endDate = selectData?.endDate || moment().format(dayFormat);
      }
      this.setState({ selectData, queryParams }, () => {
        this.getTableData();
        this.getUserOrganizationCloumns();
        this.getHospitalAuthorization();
        this.setState({ queryHeight: this.queryRef?.current?.clientHeight || 78 });
      });
    } catch (error) {
      this.setState({ selectData: {} });
    }
  }

  // 获取表头数据
  getTableColumns = async () => {
    try {
      const { categoryData } = this.state;
      let data = {
        params: [{
          compontName: categoryData?.interfaceType === 'reviewed' ? 'EssentialInformationGroupAudit' : 'EssentialInformationGroup',
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let columns = res.result && res.result.C && res.result.C.length > 0 ? res.result.C.map((item, index) => {
        return {
          ...item,
          index,
          render: (text, record) => {
            if (item.dataIndex === 'usedCount') {
              return (
                <span className="span" style={{ padding: '0 6px' }} onClick={(e) => this.handleUsedCountClick(record, e)}>{text}</span>
              );
            } else if ((item.dataIndex === 'statusDesc' && text === '实效') || (item.dataIndex === 'auditStatusDesc' && (text === '审核拒绝' || text === '修改拒绝'))) {
              return (
                <span className="common-record-delete-span">{text}</span>
              );
            } else {
              return text;
            }
          }
        }
      }) : [];
      if (columns && columns.length > 0) {
        this.setState({
          columns,
          totalWidth: res.totalWidth
        })
      }
      // 表单操作数据
      let baseInfoFormData = res.result?.formData || [];
      if (baseInfoFormData && baseInfoFormData.length > 0) {
        this.setState({ baseInfoFormData });
      }
    } catch (error) {
      console.log(error)
    }
  }

  // 查看使用机构
  handleUsedCountClick = (record, e) => {
    e.stopPropagation();
    let userOrganizationTableData = record?.hospArr || [];
    if (userOrganizationTableData && userOrganizationTableData.length > 0) {
      this.setState({ userOrganizationTableData }, () => {
        this.modalRef && this.modalRef.showModal();
      })
    } else {
      message.warning('暂无机构数据');
    }
  }

  // 获取使用机构列表表头数据
  getUserOrganizationCloumns = async () => {
    try {
      let data = {
        params: [{
          compontName: 'EIGUserOrganization',
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let columns = res.result && res.result.C && res.result.C.length > 0 ? res.result.C : [];
      if (columns && columns.length > 0) {
        this.setState({
          userOrganizationCloumns: columns,
          userOrganizationTotalWidth: res.totalWidth
        })
      }
    } catch (error) {
      console.log(error)
    }
  }

  // 切换品牌查询品种
  handleStkBrandIDChange = async (e, isResetVarietyID) => {
    try {
      let data = {
        params: [{
          desc: '',
          brandID: e,
        }]
      }
      let res = await React.$asyncPost(this, '17060005', data);
      this.setState({ stkVarietySelectData: res.result?.rows || [] }, () => {
        isResetVarietyID !== 'N' && this.baseInfoFormRef && this.baseInfoFormRef.setFieldsValue({ stkVarietyID: undefined });
      });
    } catch (error) {
      this.setState({ stkVarietySelectData: [] });
    }
  }

  // 获取收费项表单数据
  getChargesFormData = async () => {
    try {
      let data = {
        params: [{
          compontName: 'EssentialInformationGroupCharges',
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      // 表单操作数据
      let chargesFormData = res.result?.formData || [];
      if (chargesFormData && chargesFormData.length > 0) {
        this.setState({ chargesFormData });
      }
    } catch (error) {
      console.log(error)
    }
  }

  // 获取别名表头数据
  getAliasColumns = () => {
    const aliasColumns = [{
      title: '描述',
      dataIndex: 'medAlias',
      required: 'Y',
      editable: 'Y',
      align: 'center',
      inputType: 'Input',
    }];
    this.setState({ aliasColumns })
  }

  // 按医院授权供应商表头数据
  getHospitalAuthorization = () => {
    let { selectData } = this.state;
    const authorizationColumns = [{
      title: '客户名称',
      dataIndex: 'hospDesc',
      required: 'Y',
      editable: 'Y',
      align: 'center',
      inputType: 'Select',
      width: '300px',
      detailitem: selectData?.hosp || []
    }, {
      title: '供应商名称',
      dataIndex: 'vendorDesc',
      required: 'Y',
      editable: 'Y',
      align: 'center',
      inputType: 'Select',
      // width: '300px',
      detailitem: selectData?.vendor || []
    }];
    this.setState({ authorizationColumns });
  }

  // 获取医院信息表单数据
  getHospInfoFormData = async () => {
    try {
      let data = {
        params: [{
          compontName: 'EssentialInformationGroupOther',
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      // 表单操作数据
      let hospInfoFormData = res.result?.formData || [];
      if (hospInfoFormData && hospInfoFormData.length > 0) {
        this.setState({ hospInfoFormData });
      }
    } catch (error) {
      console.log(error);
    }
  }

  // 获取医院信息表单数据
  getConserveFormData = async () => {
    try {
      let data = {
        params: [{
          compontName: 'EssentialInformationGroupConserve',
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      // 表单操作数据
      let conserveFormData = res.result?.formData || [];
      if (conserveFormData && conserveFormData.length > 0) {
        this.setState({ conserveFormData });
      }
    } catch (error) {
      console.log(error);
    }
  }

  // 查询
  handleQuery = () => {
    this.setState({ page: 1 }, () => {
      this.getTableData('Y');
    })
  }

  // 请求列表数据
  getTableData = async (isReset) => {
    try {
      this.setState({ loading: true })
      let { queryParams, categoryData, pageSize, page } = this.state;
      let data = {
        params: [{
          ...queryParams,
          // S - 提交页面; A - 审核页面  
          type: categoryData?.interfaceType === 'reviewed' ? 'A' : 'S',
          // Y - 启用; N - 查全部
          useFlag: queryParams.useFlag && categoryData?.interfaceType === 'create' ? 'Y' : 'N',
        }],
        pagination: [{
          pageSize,
          currentPage: page
        }]
      }
      let res = await React.$asyncPost(this, '17060002', data);
      let tableData = res.result && 'rows' in res.result ? Util.addKeyValueToDataSource(res.result.rows) : [];
      this.setState({ tableData, total: res.result.total, loading: false }, () => {
        isReset !== 'N' && this.handleAdd();
      });
    } catch (error) {
      this.setState({ tableData: [], total: 0, loading: false }, () => {
        isReset !== 'N' && this.handleAdd();
      });
    }
  }

  // 分页操作
  compilePage = (page, pageSize) => {
    this.setState({ page, pageSize }, () => {
      this.getTableData();
    })
  }

  // 操作行
  onClickRowPublic = (record) => {
    const { categoryData, rowData } = this.state;
    const idIndex = categoryData?.idIndex || 'stockID';
    return {
      // 单击行选中
      onClick: () => {
        if (this.state.rowID === '' || (this.state.rowID && (this.state.rowID !== record[idIndex]))) {
          // 创建界面切换有修改需提醒
          if (this.isModifyForm() && categoryData?.interfaceType === 'create' && ((rowData?.auditStatus === '' || rowData?.auditStatus === '10' || rowData?.auditStatus === '25') || (rowData?.auditStatus === '30' && rowData?.modifyStatus === '10' || rowData?.modifyStatus === '25'))) {
            Modal.confirm({
              title: (
                <div>
                  数据修改提醒
                  <Icon className="common-modal-confirm-close" type="close" onClick={this.handleCloseModal} />
                </div>
              ),
              content: '当前产品信息已被修改，需要' + (rowData?.auditStatus !== '30' ? '保存' : '提交修改') + '吗？',
              okText: rowData?.auditStatus !== '30' ? '保存' : '提交修改',
              cancelText: rowData?.auditStatus !== '30' ? '不保存' : '取消',
              onOk: rowData?.auditStatus !== '30' ? () => this.handleSave(() => this.handleSelectRowData(record), '10') : () => this.handleModifyDataStatus('20'),
              onCancel: () => this.handleSelectRowData(record),
            });
          } else {
            this.handleSelectRowData(record);
          }
        } else {
          this.setState({ rowID: '' }, () => {
            this.handleResetFields();
          })
        }
      }
    }
  }

  // 确定选择
  handleSelectRowData = (record) => {
    const { categoryData } = this.state;
    const idIndex = categoryData?.idIndex || 'stockID';
    this.setState({ rowID: record[idIndex] }, () => {
      this.queryRowDataByID();
    })
  }

  // 选中行操作
  setRowClassNamePublic = (record) => {
    const { categoryData } = this.state;
    const idIndex = categoryData?.idIndex || 'stockID';
    return record[idIndex] === this.state.rowID ? 'clickRowStyle' : '';
  }

  // 查询明细数据 - stockID入参存在为另存
  queryRowDataByID = async (stockID) => {
    try {
      this.setState({ detailLoading: true });
      let { rowID, selectData, categoryData, changeFlag } = this.state;
      const idIndex = categoryData?.idIndex || 'stockID';
      let data = {
        params: [{
          // S - 提交页面; A - 审核页面  
          type: categoryData?.interfaceType === 'reviewed' ? 'A' : 'S',
          // stockID: stockID ? stockID : rowID,
          [idIndex]: stockID ? stockID : rowID, // 审核界面传入记录ID，提交界面传入库存项ID
        }]
      }
      let res = await React.$asyncPost(this, '17060003', data);
      let rowData = res.result;
      let copyRowData = JSON.parse(JSON.stringify(rowData));
      if (stockID) { // 另存情况状态数据
        rowData.stockID = '';
        rowData.chargeID = '';
        rowData.medID = '';
        rowData.auditStatus = '';
        rowData.modifyStatus = '';
        rowData.updateObj = {};
      }
      let updateObj = rowData?.updateObj?.modifyJson || {};
      let currentUpdateObj = {}; // 实际修改的数据
      // 提交修改和退回提交展示痕迹
      if (typeof (updateObj) === 'object' && JSON.stringify(updateObj) !== '{}' && rowData?.auditStatus === '30' && (rowData?.modifyStatus === '20' || rowData?.modifyStatus === '25' || (categoryData?.interfaceType === 'reviewed' && rowData?.modifyStatus === '30'))) {
        let diffData = [], oldData = {}, newData = {};
        for (var keys in updateObj) {
          for (var rowKeys in rowData) {
            if (keys === rowKeys && String(updateObj[keys]) !== String(rowData[rowKeys])) {
              currentUpdateObj[keys] = updateObj[keys]
              let formData = this.getTheCorrespondingFromData(keys);
              let formItemData = Util.returnDataCccordingToAttributes(formData, keys, 'dataIndex');
              let selectDataKey = formItemData?.className;
              let typeCode = formItemData?.typeCode;
              let newVal = typeCode === 'Select' && updateObj[keys] && selectData[selectDataKey] ? Util.returnDataCccordingToAttributes(selectData[selectDataKey], updateObj[keys], 'id').descripts : updateObj[keys];
              let oldVal = typeCode === 'Select' && rowData[rowKeys] && selectData[selectDataKey] ? Util.returnDataCccordingToAttributes(selectData[selectDataKey], rowData[rowKeys], 'id').descripts : rowData[rowKeys];
              newData[keys] = newVal;
              oldData[keys] = oldVal;
              diffData.push({
                id: 'linkID_' + keys,
                dataIndex: keys,
                title: formItemData?.title,
                new: newVal,
                old: oldVal
              })
            }
          }
        }
        rowData.diffData = diffData;
        rowData = { ...rowData, ...updateObj }; // 界面展示修改后的值
      }
      this.setState({ rowData, copyRowData, detailLoading: false }, () => {
        this.setColumnsLinkUrl('baseInfoFormData', currentUpdateObj);
        this.setColumnsLinkUrl('hospInfoFormData', currentUpdateObj);
        this.setColumnsLinkUrl('conserveFormData', currentUpdateObj);
        let hospVendorArr = rowData?.hospVendorArr || [];
        if (stockID) { // 另存过滤医院授权供应商关联ID
          for (let i = 0; i < hospVendorArr.length; i++) {
            hospVendorArr[i].productLinkHospVendorID = undefined;
            hospVendorArr[i].statusFlag = 'I'; // 未变化标志
          }
        }
        this.authorizationRef && this.authorizationRef.getTableData(hospVendorArr, '', categoryData?.interfaceType === 'reviewed' || rowData?.auditStatus === '20' || rowData?.modifyStatus === '20' ? 'statusFlag' : '', changeFlag);
        // let { rowData } = this.state;
        // !stockID && this.aliasRef && this.aliasRef.getTableData(rowData?.medAliasArr || []);
        // this.handleStkBrandIDChange(rowData?.stkBrandID || [], 'N');
      })
    } catch (error) {
      this.setState({ detailLoading: false });
    }
  }

  // 根据dataIndex获取对应的表头数据
  getTheCorrespondingFromData = (dataIndex) => {
    let { baseInfoFormData, hospInfoFormData, conserveFormData } = this.state;
    let formData = [];
    for (var i = 0; i < baseInfoFormData.length; i++) {
      if (baseInfoFormData[i].dataIndex === dataIndex) {
        formData = baseInfoFormData;
        break;
      }
    }
    if (!(formData && formData.length > 0)) { // 不存在时再去hospInfoFormData中查找
      for (var i = 0; i < hospInfoFormData.length; i++) {
        if (hospInfoFormData[i].dataIndex === dataIndex) {
          formData = hospInfoFormData;
          break;
        }
      }
    }
    if (!(formData && formData.length > 0)) { // 不存在时再去hospInfoFormData中查找
      for (var i = 0; i < conserveFormData.length; i++) {
        if (conserveFormData[i].dataIndex === dataIndex) {
          formData = conserveFormData;
          break;
        }
      }
    }
    return formData;
  }

  setColumnsLinkUrl = (cloumnsIndex, updateObj) => {
    const { rowData, categoryData } = this.state;
    for (let i = 0; i < this.state[cloumnsIndex].length; i++) {
      this.state[cloumnsIndex][i].linkUrl = '';
      for (let updateKey in updateObj) {
        if (this.state[cloumnsIndex][i].dataIndex === updateKey && rowData?.auditStatus === '30' && (rowData?.modifyStatus === '20' || rowData?.modifyStatus === '25' || (categoryData?.interfaceType === 'reviewed' && rowData?.modifyStatus === '30'))) {
          this.state[cloumnsIndex][i].linkUrl = 'linkID_' + updateKey;
        }
      }
    }
    this.setState({});
  }

  // 重置操作数据
  handleResetFields = () => {
    this.setState({ rowData: {} });
    this.baseInfoFormRef && this.baseInfoFormRef.resetFields();
    this.chargesFormRef && this.chargesFormRef.resetFields();
    this.hospInfoFormRef && this.hospInfoFormRef.resetFields();
    // this.aliasRef && this.aliasRef.resetFields();
    this.authorizationRef && this.authorizationRef.resetFields();
    this.conserveInfoFormRef && this.conserveInfoFormRef.resetFields();
    this.setColumnsLinkUrl('baseInfoFormData', {});
    this.setColumnsLinkUrl('hospInfoFormData', {});
    this.setColumnsLinkUrl('conserveFormData', {});
  }

  // 新增
  handleAdd = () => {
    this.setState({ rowID: '' }, () => {
      this.handleResetFields();
    })
  }

  // 导出
  handleExport = async () => {
    try {
      this.setState({ exportLoading: true });
      let { queryParams } = this.state;
      let data = {
        params: [{
          ...queryParams,
        }]
      }
      let res = await React.$asyncPost(this, '17060006', data);
      handleExcel.downloadExcel(res.result);
      this.setState({ exportLoading: false });
    } catch (error) {
      this.setState({ exportLoading: false });
    }
  }

  // 处理医院授权供应商数据 - 必须传: I - 新增; D - 删除; N - 无变化 
  filterHospVendorValArr = (arr) => {
    const { rowData } = this.state;
    let hospVendorArr = rowData?.hospVendorArr || [];
    let filterArr = [];
    for (let i = 0; i < arr.length; i++) {
      let currentItem = arr[i];
      if (currentItem?.statusFlag === 'M') {
        let currentVendorRecord = Util.returnDataCccordingToAttributes(hospVendorArr, currentItem.productLinkHospVendorID, 'productLinkHospVendorID')
        filterArr = [...filterArr, {
          ...currentVendorRecord,
          statusFlag: 'D'
        }, {
          ...arr[i],
          productLinkHospVendorID: '',
          statusFlag: 'I'
        }]
      } else {
        filterArr.push({
          ...arr[i],
          statusFlag: 'statusFlag' in currentItem && currentItem.statusFlag ? currentItem.statusFlag : currentItem.productLinkHospVendorID ? 'N' : 'I'
        })
      }
    }
    return filterArr;
  }

  // 保存
  handleSave = Util.debounce(async (fn, typeCode) => {
    let baseInfoVal = await this.baseInfoFormRef.handleSave();
    if (baseInfoVal && baseInfoVal.error) {
      message.error('请完善基本信息。');
      return;
    }
    let hospVal = await this.hospInfoFormRef.handleSave();
    if (hospVal && hospVal.error) {
      message.error('请完善批准文号相关信息。');
      return;
    }
    let conserveVal = await this.conserveInfoFormRef.handleSave();
    if (conserveVal && conserveVal.error) {
      message.error('请完善储运养护相关信息。');
      return;
    }
    let hospVendorVal = this.authorizationRef && this.authorizationRef.handleSave();
    if (('editingKey' in hospVendorVal) && hospVendorVal.editingKey) { // 按客户授权供应商
      message.error('客户授权供应商存在列处于编辑状态，请先保存或取消该操作。');
      return;
    }
    let { rowID } = this.state;
    fn && fn(typeCode, {
      ...baseInfoVal,
      ...hospVal,
      ...conserveVal,
      stockID: rowID || undefined,
      hospVendorArr: this.filterHospVendorValArr(hospVendorVal?.tableData || []),
      baseArr: this.getBaseArr(),
    })
  })

  // 基本信息保存 
  handleBaseInfoSave = async (statusCode, baseObj) => {
    try {
      this.setState({ saveLoading: true });
      let data = {
        params: [{
          status: statusCode,
          ...baseObj,
        }]
      }
      let res = await React.$asyncPost(this, '17060004', data);
      message.success(res.errorMessage || '保存成功');
      this.setState({ saveLoading: false });
      this.getTableData();
    } catch (error) {
      this.setState({ saveLoading: false });
    }
  }

  getBaseArr = () => {
    const { rowData, baseInfoFormData, hospInfoFormData, conserveFormData } = this.state;
    let nRowData = JSON.parse(JSON.stringify(rowData));
    if (!(nRowData && 'stockID' in nRowData && nRowData.stockID)) { // 另存清空对比数据
      nRowData = {};
    }
    let baseValues = this.baseInfoFormRef && this.baseInfoFormRef.getFieldsValue('N');
    let baseDiffData = Util.getDiffData(baseValues, nRowData, baseInfoFormData);
    let hospInfoValues = this.hospInfoFormRef && this.hospInfoFormRef.getFieldsValue('N');
    let hospInfoDiffData = Util.getDiffData(hospInfoValues, nRowData, hospInfoFormData);
    let conserveValues = this.conserveInfoFormRef && this.conserveInfoFormRef.getFieldsValue('N');
    let conserveDiffData = Util.getDiffData(conserveValues, nRowData, conserveFormData);
    return [...baseDiffData, ...hospInfoDiffData, ...conserveDiffData];
  }

  // 新增产品别名
  handleAliasAdd = () => {
    this.aliasRef && this.aliasRef.handleAddTableData();
  }

  // 判断表单信息是否修改
  isModifyForm = (returnType = '') => {
    let { rowData } = this.state;
    let baseValues = this.baseInfoFormRef && this.baseInfoFormRef.getFieldsValue('N');
    let hospValues = this.hospInfoFormRef && this.hospInfoFormRef.getFieldsValue('N');
    let conserveValues = this.conserveInfoFormRef && this.conserveInfoFormRef.getFieldsValue('N');
    let values = { ...baseValues, ...hospValues, ...conserveValues };
    let isModify = Util.isModifyForm(values, rowData, returnType);
    return isModify;
  }

  handleCloseModal = () => {
    Modal.destroyAll();
  }

  // 另存
  handleSaveAs = (record, e) => {
    e.stopPropagation();
    this.setState({ rowID: '' });
    this.queryRowDataByID(record?.stockID || '');
  }

  // 录入顺序
  handleEntrySequence = (formRefIndex) => {
    let componentName = formRefIndex === 'baseInfoFormRef' ? 'EssentialInformationGroup' : ( // 基本信息
      formRefIndex === 'conserveInfoFormRef' ? 'EssentialInformationGroupConserve' : ( // 储运养护信息
        formRefIndex === 'hospInfoFormRef' ? 'EssentialInformationGroupOther' : '')); // 批准文号信息
    this[formRefIndex] && this[formRefIndex].showFromMaintenanceModal(componentName);
  }

  // 添加授权医院
  handleHospAuthorizationAdd = () => {
    this.authorizationRef && this.authorizationRef.handleAddTableData();
  }

  // 供应商过滤
  handleFilterAuthorizationData = () => {
    const { authorizationValue } = this.state;
    this.authorizationRef && this.authorizationRef.handleFilterTableData(authorizationValue);
  }

  // 修改库存项状态 - 拒绝时传入25，审核通过传入30
  handleModifyDataStatus = async (statusCode, baseObj = {}, compnentSource, remark) => {
    try {
      this.setState({ saveLoading: true });
      const { rowData, categoryData } = this.state;
      let modifyJson = {};
      if (categoryData?.interfaceType === 'create' && rowData?.auditStatus === '30' && (rowData?.modifyStatus === '10' || rowData?.modifyStatus === '25' || rowData?.modifyStatus === '30')) {
        let modifyForm = this.isModifyForm('obj');
        let oldModifyJson = rowData?.updateObj?.modifyJson || {};
        // 退回的时候需和历史修改的数据一并保存
        modifyJson = rowData?.modifyStatus === '25' ? { ...oldModifyJson, ...modifyForm } : { ...modifyForm }
      }
      let data = {
        params: [{
          stockID: rowData?.stockID || '',
          type: rowData?.auditStatus !== '30' ? 'INSERT' : 'UPDATE', // INSERT-新增时 / UPDATE-修改
          status: statusCode,
          remark: remark || undefined, // 拒绝备注
          updateValue: categoryData?.interfaceType === 'create' ? {
            ...baseObj,
            ...modifyJson,
            modifyJson, // 需要修改的数据 - 提交修改时传入
          } : {},
        }]
      }
      let res = await React.$asyncPost(this, '17060082', data);
      message.success(res?.errorMessage || '操作成功');
      this.setState({ saveLoading: false });
      this.returnOrderRef && this.returnOrderRef.modifyVisible(false, '', '', 'Y');
      this.getTableData('Y');
    } catch (error) {
      this.setState({ saveLoading: false });
    }
  }

  // 退回
  handleReturn = () => {
    this.returnOrderRef && this.returnOrderRef.modifyVisible(true, {}, '25');
  }

  // 修改操作框数据
  handleModifyInputValue = (e, dataIndex) => {
    this.state.queryParams[dataIndex] = e;
    this.setState({}, () => {
      if (dataIndex === 'vendorID' || dataIndex === 'statusType' || dataIndex === 'status' || dataIndex === 'useFlag') {
        this.handleQuery();
      }
    })
  }

  // 查看审核记录
  handleAuditRecord = (record, e) => {
    React.$stopPropagation(e);
    this.auditRecordRef && this.auditRecordRef.modifyVisible(true, record, 'EssentialInformationGroup');
  }

  handleChangeFlagChange = e => {
    const { authorizationValue } = this.state;
    let changeFlag = e.target.checked
    this.authorizationRef && this.authorizationRef.handleFilterTableData(authorizationValue, 'statusFlag', changeFlag);
    this.setState({ changeFlag });
  }

  // 还原修改
  handleCancelModify = () => {
    let { copyRowData, changeFlag } = this.state;
    let rowData = copyRowData;
    rowData.cancelModifyFlag = 'Y';
    let hospVendorArr = rowData?.hospVendorArr || [];
    for (let i = 0; i < hospVendorArr.length; i++) {
      hospVendorArr[i].statusFlag = ''; // 未变化标志
    }
    hospVendorArr = hospVendorArr.filter(item => !!item.productLinkHospVendorID)
    this.setState({ rowData, hospVendorArr }, () => {
      this.setColumnsLinkUrl('baseInfoFormData', {});
      this.setColumnsLinkUrl('hospInfoFormData', {});
      this.authorizationRef && this.authorizationRef.getTableData(hospVendorArr, '', '', changeFlag);
    });
  }

  render() {
    let { columns, totalWidth, tableData, page, total, loading, selectData, rowID, rowData, baseInfoFormData, exportLoading, categoryData, queryParams, queryHeight, detailLoading, changeFlag,
      saveLoading, userOrganizationCloumns, userOrganizationTableData, hospInfoFormData, authorizationColumns, authorizationValue, conserveFormData
    } = this.state;

    // 列表操作
    const operationObj = {
      width: 120,
      title: '操作',
      align: 'center',
      key: 'operation',
      fixed: 'right',
      render: (text, record) => (
        <>
          <span className="span" onClick={(e) => this.handleSaveAs(record, e)}>
            另存
          </span>
          <Divider type="vertical" />
          <span className="span" onClick={(e) => this.handleAuditRecord(record, e)}>
            {record?.tip === 'Y' ? (
              <Badge dot>
                审核记录
              </Badge>
            ) : '审核记录'}
          </span>
        </>
      ),
    };

    const modalParams = {
      isMask: 'Y',
      title: '使用机构列表',
      componentName: 'EIGUserOrganization',
      columns: userOrganizationCloumns, // 使用机构表头数据
      data: userOrganizationTableData,
    };
    return (
      <div className="essential-information">
        <Row>
          <Col span={10}>
            <div
              style={{ paddingRight: '6px', position: 'relative', height: '100%' }}
            >
              <Card
                size="small"
                className="ei-card ei-left-card"
                title={(
                  <div className="card-title-left-img">
                    <img src={iconListvisits} alt="" />
                    {categoryData?.interfaceType === 'reviewed' ? '产品审核记录' : '产品列表'}
                  </div>
                )}
                extra={(
                  categoryData?.interfaceType === 'reviewed' ? '' : <Checkbox checked={queryParams?.useFlag || false} onChange={(e) => this.handleModifyInputValue(e.target.checked, 'useFlag')}>仅显示启用</Checkbox>
                )}
              >
                <div className="table-body-height">
                  <div ref={this.queryRef}>
                    <div className="flex-align-items" style={{ marginBottom: 12 }}>
                      {categoryData?.interfaceType === 'reviewed' ? (
                        <>
                          <div className="flex-align-items" style={{ marginRight: '15px' }}>
                            <span className="common-input-label">日期：</span>
                            <RangeDatePicker
                              width="300px"
                              format="YYYY-MM-DD"
                              isChange={true}
                              endDate={queryParams?.endDate || undefined}
                              startDate={queryParams?.startDate || undefined}
                              endChange={(e) => this.handleModifyInputValue(e, 'endDate')}
                              startChange={(e) => this.handleModifyInputValue(e, 'startDate')}
                            />
                          </div>
                        </>
                      ) : ''}
                      <span className="common-input-label">产品信息：</span>
                      <Input
                        title="输入内容后可回车检索"
                        placeholder="输入代码/描述查询"
                        className="common-query-input"
                        value={queryParams?.desc}
                        onChange={(e) => this.handleModifyInputValue(e.target.value, 'desc')}
                        onPressEnter={this.handleQuery}
                      />
                      {categoryData?.interfaceType === 'reviewed' ? '' : (
                        <>
                          <span className="common-input-label">产品子类：</span>
                          <Select
                            allowClear
                            showSearch
                            placeholder="请选择"
                            optionFilterProp="seachprop"
                            className="common-query-input"
                            value={queryParams?.stkSubCatID}
                            onChange={(e) => this.handleModifyInputValue(e, 'stkSubCatID')}
                          >
                            {selectData && selectData.ordSubCat ? React.$SelectOptions(selectData.ordSubCat) : ''}
                          </Select>
                        </>
                      )}
                      <Button type="primary" style={{ marginRight: 12 }} onClick={this.handleQuery}>查询</Button>
                      {categoryData?.interfaceType === 'reviewed' ? '' : (
                        <Button
                          ghost
                          type="primary"
                          loading={exportLoading}
                          onClick={this.handleExport}
                        >
                          {exportLoading ? '导出中……' : '导出'}
                        </Button>
                      )}
                    </div>
                    <div style={{ marginTop: '12px', display: categoryData?.interfaceType === 'reviewed' ? 'block' : 'none' }}>
                      <span className="common-input-label">审核类型：</span>
                      <Radio.Group value={queryParams?.statusType} onChange={(e) => this.handleModifyInputValue(e.target.value, 'statusType')}>
                        {selectData && 'statusType' in selectData && Array.isArray(selectData.statusType) && selectData.statusType.map((item, index) => {
                          return (
                            <Radio key={index} value={item.id}>{item.descripts + (item && 'count' in item ? '(' + item.count + ')' : '')}</Radio>
                          )
                        })}
                      </Radio.Group>
                    </div>
                    <div style={{ margin: '12px 0' }}>
                      <span className="common-input-label">审核状态：</span>
                      <Radio.Group value={queryParams?.status} onChange={e => this.handleModifyInputValue(e.target.value, 'status')}>
                        {selectData && 'status' in selectData && Array.isArray(selectData.status) && selectData.status.map((item, index) => {
                          return (
                            <Radio key={index} value={item.id}>{item.descripts + (item && 'count' in item ? '(' + item.count + ')' : '')}</Radio>
                          )
                        })}
                      </Radio.Group>
                    </div>
                  </div>
                  <PubilcTablePagination
                    param={{
                      page,
                      total,
                      loading,
                      pageSize: '20',
                      data: tableData, // 表格数据
                      x: totalWidth, // 表格的宽度
                      y: store.getState().tableHeight.y + 75 - queryHeight,
                      height: store.getState().tableHeight.y + 125 - queryHeight + 'px',
                      componentName: 'EssentialInformationGroup',
                      columns: columns && columns.length > 0 ? (categoryData?.interfaceType === 'reviewed' ? columns : [...columns, operationObj]) : [...this.staticColumns, operationObj], // 表头配置
                    }}
                    compilePage={this.compilePage}
                    getColumns={this.getTableColumns}
                    onClickRowPublic={this.onClickRowPublic}
                    setRowClassNamePublic={this.setRowClassNamePublic}
                  />
                </div>
              </Card>
              <div className="common-card-right-split-line" style={{ width: 8 }}></div>
            </div>
          </Col >
          <Col span={14}>
            <Card
              size="small"
              className="ei-card ei-right-card"
              title={(
                <div className="card-title-left-img">
                  <img src={iconListvisits} alt="" />
                  {(categoryData?.interfaceType === 'reviewed' && rowData?.auditStatus === '30' && rowData?.modifyStatus === '20') || (categoryData?.interfaceType === 'create' && (rowData?.auditStatus === '20' || rowData?.modifyStatus === '20')) ? (
                    categoryData?.interfaceType === 'create' ? (
                      <span>【{rowData?.medDesc || ''}】已提交审核，请耐心等待。</span>
                    ) : (
                      <span>您可以点击下划线上的文字查看修改前的数据</span>
                    )
                  ) : (
                    <div className="flex">
                      {'正在' + (categoryData?.interfaceType === 'reviewed' ? '查看' : (rowID ? '修改' : '添加')) + '视光产品信息'}
                      <span
                        title={rowData?.recordRemark || ''}
                        className="common-record-delete-span ellipsis"
                        style={{
                          display: (rowData?.auditStatus === '25' || rowData?.modifyStatus === '25') ? 'inline-block' : 'none',
                          maxWidth: '36vw'
                        }}
                      >
                        【退回原因：{rowData?.recordRemark || ''}】
                      </span>
                    </div>
                  )}
                </div>
              )}
              extra={rowID && categoryData?.interfaceType === 'create' ? <Button
                icon="plus"
                className="add-btn add-btn-nohover"
                onClick={this.handleAdd}
              >
                新增产品
              </Button> : ''}
            >
              <Spin spinning={detailLoading} tip="数据加载中……">
                <div className="ei-right-card-content scroll-bar-style" style={{ height: store.getState().tableHeight.y + 138 }}>
                  <Card
                    type="inner"
                    size="small"
                    title="基本信息"
                    extra={(
                      categoryData?.entrySequenceBtnFlag !== 'N' ? (
                        <Button
                          size="small"
                          onClick={() => this.handleEntrySequence('baseInfoFormRef')}
                        >
                          录入顺序
                        </Button>
                      ) : ''
                    )}
                  >
                    <DynamicRenderingForm
                      formItemCol={{ labelCol: 9, wrapperCol: 15 }}
                      rowData={rowData}
                      selectData={selectData}
                      formData={baseInfoFormData}
                      onRef={ref => this.baseInfoFormRef = ref}
                    />
                  </Card>
                  <Card
                    type="inner"
                    size="small"
                    title="批准文号"
                    style={{ margin: '12px 0' }}
                    extra={(
                      categoryData?.entrySequenceBtnFlag !== 'N' ? (
                        <Button
                          size="small"
                          onClick={() => this.handleEntrySequence('hospInfoFormRef')}
                        >
                          录入顺序
                        </Button>
                      ) : ''
                    )}
                  >
                    <DynamicRenderingForm
                      formItemCol={{ labelCol: 9, wrapperCol: 15 }}
                      rowData={rowData}
                      selectData={selectData}
                      formData={hospInfoFormData && hospInfoFormData.length > 0 ? hospInfoFormData : this.staticHospInfoFormData}
                      onRef={ref => this.hospInfoFormRef = ref}
                    />
                  </Card>
                  <Card
                    type="inner"
                    size="small"
                    title="储运养护信息"
                    style={{ margin: '12px 0' }}
                    extra={(
                      categoryData?.entrySequenceBtnFlag !== 'N' ? (
                        <Button
                          size="small"
                          onClick={() => this.handleEntrySequence('conserveInfoFormRef')}
                        >
                          录入顺序
                        </Button>
                      ) : ''
                    )}
                  >
                    <DynamicRenderingForm
                      formItemCol={{ labelCol: 9, wrapperCol: 15 }}
                      rowData={rowData}
                      selectData={selectData}
                      formData={conserveFormData}
                      onRef={ref => this.conserveInfoFormRef = ref}
                    />
                  </Card>
                  <Card
                    type="inner"
                    size="small"
                    title="按客户授权供应商"
                    style={{ marginBottom: '12px' }}
                  >
                    <div className="flex-between-center" style={{ marginBottom: '12px' }}>
                      <Input
                        placeholder="输入客户/供应商名称查询"
                        style={{ width: '300px' }}
                        prefix={<Icon type="search" />}
                        value={authorizationValue}
                        onChange={Util.commonInputChange.bind(this, 'authorizationValue')}
                        onPressEnter={this.handleFilterAuthorizationData}
                      />
                      {categoryData?.interfaceType === 'reviewed' || rowData?.auditStatus === '20' || rowData?.modifyStatus === '20' ? (
                        <div className="flex-align-items">
                          <span style={{ display: 'inline-block', width: '16px', height: '16px', marginRight: '6px', background: '#b9eddf', borderRadius: '2px' }}></span>本次新增
                          <Checkbox style={{ marginLeft: '24px' }} checked={changeFlag} onChange={this.handleChangeFlagChange}>仅查看变化</Checkbox>
                        </div>
                      ) : (
                        <Button
                          icon="plus"
                          type="link"
                          onClick={this.handleHospAuthorizationAdd}
                        >
                          添加授权客户
                        </Button>
                      )}
                    </div>
                    <PublicTableEditable
                      revertFlag={categoryData?.revertFlag || 'Y'}
                      operationFlag={categoryData?.interfaceType === 'reviewed' ? 'N' : 'Y'}
                      deleteCode="addDeleteFlag"
                      filterDataIndex={['vendorDesc', 'hospDesc']}
                      recordID="productLinkHospVendorID"
                      columns={authorizationColumns}
                      onRef={ref => this.authorizationRef = ref}
                    />
                  </Card>
                </div>
              </Spin>
              <div className="ei-right-card-footer">
                <div className="ei-right-card-footer-content flex-center">
                  {categoryData?.interfaceType === 'reviewed' ? ( // 审核
                    <>
                      {rowData?.auditStatus === '20' || rowData?.modifyStatus === '20' ? (
                        <Popconfirm
                          title="确定要退回吗?"
                          onConfirm={this.handleReturn}
                        >
                          <Button
                            ghost
                            type="danger"
                          >
                            审核不通过
                          </Button>
                        </Popconfirm>
                      ) : (
                        <Button
                          type="danger"
                          disabled
                        >
                          审核不通过
                        </Button>
                      )}
                      <Button
                        type="primary"
                        loading={saveLoading}
                        style={{ marginLeft: '12px' }}
                        disabled={!(rowData?.auditStatus === '20' || rowData?.modifyStatus === '20')}
                        onClick={() => this.handleModifyDataStatus('30')}
                      >
                        {saveLoading ? '审核中…' : '审核通过'}
                      </Button>
                    </>
                  ) : ( // 创建数据
                    <>
                      {categoryData?.interfaceType === 'create' && rowData?.auditStatus === '30' && rowData?.modifyStatus === '25' ? (
                        rowData?.cancelModifyFlag === 'Y' ? (
                          <Button
                            ghost
                            type="danger"
                            disabled
                            style={{ marginRight: '12px' }}
                          >
                            放弃变更
                          </Button>
                        ) : (
                          <Popconfirm
                            title="放弃变更后不可恢复，确定要放弃吗?"
                            onConfirm={this.handleCancelModify}
                          >
                            <Button
                              ghost
                              type="danger"
                              style={{ marginRight: '12px' }}
                            >
                              放弃变更
                            </Button>
                          </Popconfirm>
                        )
                      ) : ''}
                      <Button
                        type="primary"
                        loading={saveLoading}
                        disabled={!(!rowID || rowData?.auditStatus === '' || rowData?.auditStatus === '10' || rowData?.auditStatus === '25' || (rowData?.auditStatus === '30' && (rowData?.modifyStatus !== '20')))}
                        onClick={rowData?.auditStatus !== '30' ? () => this.handleSave(this.handleBaseInfoSave, '20') : () => this.handleSave(this.handleModifyDataStatus, '20')}
                      >
                        {saveLoading ? '提交中…' : ((rowData?.auditStatus === '25' || rowData?.modifyStatus === '25') && rowData?.cancelModifyFlag !== 'Y' ? '重新提交' : (rowData?.auditStatus === '30' ? '提交修改' : '提交审核'))}
                      </Button>
                    </>
                  )}
                </div>
              </div>
            </Card>
          </Col>
        </Row >
        <PublicModalTable
          param={modalParams}
          onRef={ref => this.modalRef = ref}
          getColumns={this.getUserOrganizationCloumns}
        />

        {/* 退回订单 */}
        <ReturnOrder modalTitle="退回" selectData={{}} modifyApplicationFormStatus={this.handleModifyDataStatus} onRef={ref => this.returnOrderRef = ref} />

        {/* 审核记录 */}
        <SupplierAuditRecord
          auditTableCode="17060098"
          detailCode="17060099"
          propsRowIDIndex="stockID"
          rowIDDataIndex="optStkModifyRecordID"
          interfaceType="EssentialInformationGroup"
          detailTableDataIndex="hospVendorArr"
          tabList={[{
            key: '1',
            tab: '基本信息',
          }, {
            key: '2',
            tab: '按客户授权供应商',
          }]}
          columns={authorizationColumns}
          onRef={ref => this.auditRecordRef = ref} />
      </div >
    )
  }
};

export default EssentialInformationGroup;